package com.expdatacloud.controller.iqc;

import com.expdatacloud.entity.Acknowledgment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * @author jie
 * @date 2019/11/20 -14:45
 */
@Controller
@RequestMapping("/acknowledgment")
public class AcknowledgmentController {

    /**
     * 查看承认书
     */
    @GetMapping("/showAcknowledgment")
    public String showAcknowledgment(String sku, HttpServletRequest request) throws Exception {
        String jsonStr = get(sku);
        int start = jsonStr.indexOf("[{");
        int end = jsonStr.indexOf("}]");
        if (start == -1 || end == -1){
            return "/iqc/acknowledgement";
        }
        String json = jsonStr.substring(start, end + 2);

        Gson gson = new Gson();
        List<Acknowledgment> acknowledgmentList = gson.fromJson(json, new TypeToken<List<Acknowledgment>>(){}.
                getType());
        request.setAttribute("acknowledgmentList",acknowledgmentList);
        return "/iqc/acknowledgement";
    }

    public  String get(String sku) throws Exception{
        URL url=new URL("http://192.168.113.98:38080/axis2/services/PlmService/GetCrsFilesByItemId?sPartNumber="+sku);
        HttpURLConnection conn=(HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        //结果码=200
        if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
            InputStream is=conn.getInputStream();
            //内存流 ，
            ByteArrayOutputStream boas=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len=-1;
            while((len=is.read(buffer))!=-1){
                boas.write(buffer, 0, len);
            }
            System.out.println("GET请求获取的数据:"+boas.toString());
            boas.close();
            is.close();
            return boas.toString();
        }
        return null;
    }
}
